import { createRouter, createWebHistory } from 'vue-router';
import Login from '@/views/Login.vue'; // 引入Login组件
import Home from '@/views/Home.vue';
import AdminUser  from '@/views/AdminUser.vue';
import Member from '@/views/Member.vue';
import TaskCategory from '@/views/TaskCategory.vue';
import Task from '@/views/Task.vue';
import Article from '@/views/Article.vue';
import ArticleCategory from '@/views/ArticleCategory.vue';
import UserCenter from '@/views/UserCenter.vue';
import Vip from '@/views/Vip.vue';
import TaskOrder from '@/views/taskOrder.vue';
import CashMoney from '@/views/CashMoney.vue';
import UserMoney from '@/views/UserMoney.vue';
import Basic from '@/views/Basic.vue';
import Configure from '@/views/configure.vue';
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: ()=>import('@/layout/index.vue'),
      redirect: '/adminUser',
      children: [
        {
          path: '/adminUser',
          name: '管理员',
          component: AdminUser 
        },
        {
          path: '/member',
          component: Member 
        },
        {
          path: '/taskCategory',
          component: TaskCategory 
        },
        {
          path: '/task',
          component: Task 
        },
        {
          path: '/article',
          component: Article 
        },
        {
          path: '/articleCategory',
          component: ArticleCategory 
        },
        {
          path: '/userCenter',
          component: UserCenter 
        },
        {
          path: '/vip',
          component: Vip 
        },
        {
          path: '/taskOrder',
          component: TaskOrder 
        },
        {
          path: '/cashMoney',
          component: CashMoney 
        },
        {
          path: '/userMoney',
          component: UserMoney 
        },
        {
          path: '/basic',
          component: Basic 
        },
        {
          path: '/configure',
          component: Configure 
        }
      ],
    },
    {
      path: '/login',
      name: 'Login',
      component: Login // 配置Login组件的路由
    },
    { 
      path: '/:pathMatch(.*)*', 
      name: 'NotFound', 
      component: () => import('@/views/NotFoundView.vue') 
    },
    
  ],
})

// 封装获取 token 的方法
const TOKEN_KEY = 'token';
function getToken(tokenKey = TOKEN_KEY) {
  const token = localStorage.getItem(tokenKey);

  if (token === undefined || token === null || token === '') {
    return '';
  }
  return token;
}

//路由守卫
router.beforeEach((to, from, next) => {
  // 如果用户未登录且目标路径不是 /login，则重定向到登录页面
  if (to.path !== '/login' && !getToken()) {
    next('/login');
  } else if(to.path == '/login' && getToken()) {
    // 如果用户已登录且目标路径是 /login，则重定向到首页
    next('/');
  }else {
    next();
  }
});

export default router
